package com.wtwd.campus.receiver;

import com.alibaba.fastjson.JSONObject;
import com.wtwd.campus.annotation.MsgType;
import com.wtwd.campus.common.Constants;
import com.wtwd.campus.entity.DeviceInfo;
import com.wtwd.campus.entity.MqGeneralSwitchResult;
import com.wtwd.campus.entity.MqMessage;
import com.wtwd.campus.h5_manager.entity.DeviceLog;
import com.wtwd.campus.h5_manager.service.DeviceLogService;
import com.wtwd.campus.service.DeviceInfoService;
import com.wtwd.campus.utils.PushUtils;
import com.wtwd.campus.utils.ReceiverUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@MsgType(value = Constants.SET_SOS_DIAL_SWITCH)
public class SOSDialSwitchReceiverHandler implements IReceiverHandler {
    @Autowired
    private DeviceInfoService deviceInfoService;
    @Autowired
    private ReceiverUtils receiverUtils;
    @Autowired
    private PushUtils pushUtils;
    @Autowired
    private DeviceLogService deviceLogService;
    @Override
    public void handlerMessage(MqMessage mqMessage) {
        MqGeneralSwitchResult mqGeneralSwitchResult = (MqGeneralSwitchResult) mqMessage.getObject();
        String imei = mqGeneralSwitchResult.getImei();
        String commandNumber = mqGeneralSwitchResult.getCommandNumber();
        Integer flag = mqGeneralSwitchResult.getResult();
        //处理指令回复的时间
        Long time = System.currentTimeMillis();
        DeviceInfo deviceInfo = deviceInfoService.getDeviceByImei(imei);
        if (deviceInfo != null) {
            //修改设备信息
            deviceInfo.setLastUpTime(System.currentTimeMillis());
            deviceInfoService.modifyDeviceInfo(deviceInfo);
            //删除缓存中的指令
            String delKey=Constants.SET_SOS_DIAL_SWITCH.concat("-").concat(commandNumber);
            receiverUtils.deleteCommandInRedis(imei, delKey);
            //完善指令下发记录
            receiverUtils.completeCommandRecord(Constants.SET_SOS_DIAL_SWITCH, imei, commandNumber, null, Constants.COMMAND_COMPLETE, time);
            //存储设备接收日志
            DeviceLog deviceLog = new DeviceLog();
            deviceLog.setSendUser(Constants.DEVICE_USER);
            deviceLog.setImei(imei);
            deviceLog.setBigType(Constants.MESS_TYPE);
            deviceLog.setType(Constants.SET_SOS_DIAL_SWITCH);
            JSONObject contant = new JSONObject();
            contant.put("设备号", imei);
            contant.put("0:SOS循环拨号，默认值；1关闭SOS拨号",flag);
            contant.put("设备状态",mqGeneralSwitchResult.getDeviceStatus());
            deviceLog.setCmd(contant.toJSONString());
            deviceLog.setSendTime(System.currentTimeMillis());
            deviceLog.setCommandNumber(commandNumber);
            deviceLog.setState(1);
            deviceLogService.addDeviceLog(deviceLog);
        } else {
            saveUnInStorage(imei);
            receiverUtils.cloaseChannel(imei);
        }
    }
}
